from django.db.models.query import QuerySet
from django.http import request
from django.shortcuts import get_object_or_404, render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from listings.choices import price_choices, bedroom_choices, state_choices
from .models import Listing
# Create your views here.

def index(request):
    #引入 Listing Model ，并且将它传入到网页模板中
    #list_date使用时间排序
    #只显示已发布的信息
    listings = Listing.objects.order_by('-list_date').filter(is_published=True)
    #每页多少条数据
    paginator = Paginator(listings, 3)
    page = request.GET.get('page')
    paged_listings = paginator.get_page(page)
    
    #定义context, 在 render 中传入context
    context = {'listings': paged_listings}
    return render(request, 'listings/listings.html', context)

def listing(request, listing_id):

    listing = get_object_or_404(Listing, pk=listing_id)

    context = {
        'listing': listing
    }
    return render(request, 'listings/listing.html', context)

def search(request):
    querySet_list = Listing.objects.order_by('-list_date')

    #Keywords
    if 'keywords' in request.GET:
        keywords = request.GET['keywords']
        if keywords:
            querySet_list = querySet_list.filter(
                description__icontains=keywords
            )
    #City
    if 'city' in request.GET:
        city = request.GET['city']
        if city:
            querySet_list = querySet_list.filter(
                city__iexact=city
            )
    
    #State
    if 'state' in request.GET:
        state = request.GET['state']
        if state:
            querySet_list = querySet_list.filter(
                state__iexact=state
            )

     #Bedrooms
    if 'bedrooms' in request.GET:
        bedrooms = request.GET['bedrooms']
        if bedrooms:
            querySet_list = querySet_list.filter(
                bedrooms__lte=bedrooms
            ) 
    
    #Price
    if 'price' in request.GET:
        price = request.GET['price']
        if price:
            querySet_list = querySet_list.filter(
                price__lte=price
            ) 
    context = {
        'state_choices': state_choices,
        'bedroom_choices': bedroom_choices,
        'price_choices': price_choices,
        'listings': querySet_list,
        'values': request.GET
    }
    return render(request, 'listings/search.html', context)